package com.pzl.wv.simple;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.pzl.simple.wvlib.IWebViewService;
import com.pzl.simple.wvlib.WebVeiwBrowserActivity;
import com.pzl.simple.wvlib.WebViewRemoteImpl;
import com.pzl.simple.wvlib.bean.AlertMsg;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //启动同在webview进程的service
        bindService(new Intent(this, WebViewRemoteImpl.class), connectionWebView, BIND_AUTO_CREATE);
    }


    public void click(View view) {
        switch (view.getId()) {
            case R.id.btn_load:
                Intent intent = new Intent(this, WebVeiwBrowserActivity.class);
                startActivity(intent);

                /**
                 * 调用远程进程的webview JS并传递数据
                 */
                view.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        AlertMsg alertMsg = new AlertMsg();
                        alertMsg.cmd = "showAlertMsg";
                        alertMsg.code = 200;
                        alertMsg.data = new AlertMsg.Data();
                        alertMsg.data.msg = "性能优化2020脱坑";
                        try {
                            webViewProxy.callJS("funMsg", new Gson().toJson(alertMsg));
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                }, 1000);
                break;
        }
    }


    private IWebViewService webViewProxy;
    ServiceConnection connectionWebView = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            webViewProxy = IWebViewService.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

}
